package com.example.budget3.recurring;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.example.budget3.R;
import com.example.budget3.data.ExpenseCategory;
import com.example.budget3.data.IncomeCategory;
import com.example.budget3.data.RecurrTransactionData;
import com.example.budget3.modify.EditRecurrTransaction;
import com.example.budget3.months.MainActivity;
import com.example.budget3.util.TransactionDataContract;
import com.example.budget3.util.TransactionDataContract.BillEntry;
import com.example.budget3.util.TransactionDataContract.DataEntry;
import com.example.budget3.util.TransactionDataContract.TransactionDataDbHelper;
import com.example.budget3.util.UtilMethods;
import com.haarman.listviewanimations.swinginadapters.AnimationAdapter;
import com.haarman.listviewanimations.swinginadapters.prepared.SwingBottomInAnimationAdapter;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

public class RecurrListFragment extends Fragment {
	
    public static final String ARG_MONTH_NUMBER = "month_number";
	final List<Float> items = new ArrayList<Float>();
	List<Integer> selected = new ArrayList<Integer>();
	protected int selectedPointIndex = 0;
	
	private ActionSlideExpandableListView list;
	private View listContainer;
	private Context context;
	private List<RecurrTransactionData> data;
	private RecurrListAdapter periodListAdapter;
	private RecurrListFragment frag;
	private int period;
	
	public static final String KEY_CURRENCY_PREFERENCE = "pref_currency";
	public static final String KEY_BUDGET_PREFERENCE = "pref_budget";
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			
		context = getActivity();
		Bundle args = getArguments();
		period = args.getInt("period");
		loadData();
      

		listContainer = inflater.inflate(R.layout.recurr_transaction_list, container, false);
		createList();
		
		return listContainer;
	}
	
	private void createList() {
		list = (ActionSlideExpandableListView) listContainer.findViewById(R.id.transactions_list);
		
		
		periodListAdapter = new RecurrListAdapter(getActivity(), R.layout.recurr_list_rowlayout, data);
		
		
		AnimationAdapter animAdapter = new SwingBottomInAnimationAdapter(periodListAdapter);
		animAdapter.setAbsListView(list);
		
		
		list.setAdapter(animAdapter);
		frag = this;
		list.setItemActionListener(new ActionSlideExpandableListView.OnActionClickListener() {

             @Override
             public void onClick(View listView, View buttonview, final int position) {
                     if(buttonview.getId()==R.id.deleteBtn) {
                    	 	DialogFragment newFragment = new RecurrDeleteDialogFragment();
                    	 	Bundle positionBundle = new Bundle();
                    	 	positionBundle.putInt("position", position);
							newFragment.setArguments(positionBundle);
							newFragment.setTargetFragment(frag, 1);
         		        	newFragment.show(getFragmentManager(), "change"); 
                    	 
             			}else{
             				Bundle bundle = new Bundle();
             				RecurrTransactionData entry = data.get(position);
             				bundle.putInt(EditRecurrTransaction.ENTRY_ID, entry.getId());
             				Intent editIntent = new Intent(context, EditRecurrTransaction.class);
             				editIntent.putExtras(bundle);
             				getActivity().startActivityForResult(editIntent, MainActivity.RESULT_EDIT_RECURRING);
             				
             			}
             }

     // note that we also add 1 or more ids to the setItemActionListener
     // this is needed in order for the listview to discover the buttons
     }, R.id.editBtn, R.id.deleteBtn);
	}
		
	public void removeItem(int position) {
		TransactionDataContract contract = new TransactionDataContract();
		TransactionDataDbHelper mDbHelper = contract.new TransactionDataDbHelper(
				context);
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		String selection = BillEntry._ID + " = ?";
		RecurrTransactionData item = this.data.get(position);
		// Specify arguments in placeholder order.
		String[] selectionArgs = { String.valueOf(item.getId()) };
		// Issue SQL statement.
		db.delete(BillEntry.TABLE_NAME, selection, selectionArgs);
		Toast.makeText(context, "Removed: " + item.getName(),
				Toast.LENGTH_SHORT).show();
		list.collapse();
		this.data.remove(position);
		periodListAdapter.notifyDataSetChanged();

	}

	private boolean loadData() {
		ArrayList<RecurrTransactionData> localData = new ArrayList<RecurrTransactionData>();
		TransactionDataContract contract = new TransactionDataContract();
		TransactionDataDbHelper mDbHelper = contract.new TransactionDataDbHelper(getActivity());
		SQLiteDatabase db = mDbHelper.getWritableDatabase();
		
		// Define a projection that specifies which columns from the database
		// you will actually use after this query.

		String[] selectionArgs = new String[0];
		
		String sql = "SELECT * from "+BillEntry.TABLE_NAME+" where " + BillEntry.COLUMN_NAME_PERIOD + "=" + period;
		Cursor mycursor = db.rawQuery(sql, selectionArgs);
		
	
		
		if (mycursor.moveToFirst())
		{
	        do {      
	    		String name = mycursor.getString(
	    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_NAME));
	    		float cost = mycursor.getFloat(
	    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_COST));
	    		int catOrd = mycursor.getInt(
	    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_CATEGORY));
	    		int period = mycursor.getInt(
	    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_PERIOD));
	    		String time = mycursor.getString(
	    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_NEXT_TIME));
	    		int id = mycursor.getInt(
	    				mycursor.getColumnIndexOrThrow(BillEntry._ID)); 		
	    		
	    		Date timeDate;
				try {
					timeDate =  UtilMethods.stringToDate(time);
					boolean type = mycursor.getInt(
	    				mycursor.getColumnIndexOrThrow(DataEntry.COLUMN_NAME_TYPE)) == 0 ? false:true;
					if(type){
			    		if(period == 0){
			    			int hour = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_HOUR));
			    			int minute = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_MINUTE));
			    			
			    			ExpenseCategory category = ExpenseCategory.values()[catOrd];
							localData.add( new RecurrTransactionData(id, name, cost, category, timeDate, type, period, minute, hour));
			    			
			    		}else if(period ==1){
			    			int dayOfWeek = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_DAY_OF_WEEK));
			    			
			    			ExpenseCategory category = ExpenseCategory.values()[catOrd];
							localData.add( new RecurrTransactionData(id, name, cost, category, timeDate, type, period, dayOfWeek, 0));
			    		}else {
			    			int dayOfMonth = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_DAY_OF_MONTH));
			    			ExpenseCategory category = ExpenseCategory.values()[catOrd];
							localData.add( new RecurrTransactionData(id, name, cost, category, timeDate, type, period, dayOfMonth, 0));
			    		}
						
						
						
					}else{
			    		if(period == 0){
			    			int hour = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_HOUR));
			    			int minute = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_MINUTE));
			    			
			    			IncomeCategory category = IncomeCategory.values()[catOrd];
							localData.add( new RecurrTransactionData(id, name, cost, category, timeDate, type,period, minute, hour));
			    		}else if(period ==1){
			    			int dayOfWeek = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_DAY_OF_WEEK));
			    			IncomeCategory category = IncomeCategory.values()[catOrd];
							localData.add( new RecurrTransactionData(id, name, cost, category, timeDate, type,period, dayOfWeek, 0));
			    		}else {
			    			int dayOfMonth = mycursor.getInt(
				    				mycursor.getColumnIndexOrThrow(BillEntry.COLUMN_NAME_DAY_OF_MONTH));
			    			IncomeCategory category = IncomeCategory.values()[catOrd];
							localData.add( new RecurrTransactionData(id, name, cost, category, timeDate, type,period, dayOfMonth, 0));
			    		}

					}
					
					
				} catch (ParseException e) {
				}
	        } while (mycursor.moveToNext());
		}
		if(data == null || !data.equals(localData)){
			data = localData;
			return true;
		}
		return false;
			
	}
	
	public void checkForChanges() {
		if(loadData()){
			periodListAdapter.setData(data);
			periodListAdapter.notifyDataSetChanged();
			list.collapse();
		}
	}

}
